'use client';

// 分享码预览对话框组件
// REF: API-SHARE189-004@v1.0

import React, { useState } from 'react';
import {
  Eye,
  RefreshCw,
  Plus,
  FileSearch,
  Clock,
  User,
  FolderOpen,
  HardDrive,
  Share2,
  Loader2,
  AlertCircle,
  CheckCircle,
  File
} from 'lucide-react';

import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { useToast } from '@/hooks/use-toast';
import { ImportApiService } from './api';
import { formatBytes } from './utils';
import { ExpandableFileTree } from './ExpandableFileTree';
import type { PreviewResult } from './types';

interface ShareCodePreviewDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export function ShareCodePreviewDialog({ open, onOpenChange }: ShareCodePreviewDialogProps) {
  const [shareCode, setShareCode] = useState('');
  const [accessCode, setAccessCode] = useState('');
  const [loading, setLoading] = useState(false);
  const [adding, setAdding] = useState(false);
  const [previewResult, setPreviewResult] = useState<PreviewResult | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);
  const { toast } = useToast();

  // 重命名变量以匹配新的UI
  const isLoading = loading;
  const isAdding = adding;

  const handlePreview = async () => {
    if (!shareCode.trim()) {
      setError('请输入分享码');
      return;
    }

    setLoading(true);
    setError(null);
    setSuccessMessage(null);
    try {
      const result = await ImportApiService.previewShareCode(
        shareCode.trim(),
        accessCode.trim() || undefined
      );
      setPreviewResult(result);
      setSuccessMessage('分享码内容已加载');
    } catch (error: any) {
      setError(error.message || '无法获取分享码内容，请检查分享码和访问码');
      setPreviewResult(null);
    } finally {
      setLoading(false);
    }
  };

  const handleAddToList = async () => {
    if (!previewResult) return;

    setAdding(true);
    setError(null);
    setSuccessMessage(null);
    try {
      await ImportApiService.addShareCode(
        shareCode.trim(),
        accessCode.trim() || undefined,
        `预览添加 - ${previewResult.shareInfo.title}`
      );
      setSuccessMessage('分享码已添加到管理列表');
      // 清空表单并关闭对话框
      setTimeout(() => handleClose(), 1500);
    } catch (error: any) {
      setError(error.message || '添加分享码时发生错误');
    } finally {
      setAdding(false);
    }
  };

  const handleClose = () => {
    setShareCode('');
    setAccessCode('');
    setPreviewResult(null);
    setError(null);
    setSuccessMessage(null);
    onOpenChange(false);
  };

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent className="max-w-7xl max-h-[90vh] overflow-hidden">
        <DialogHeader className="pb-4 border-b">
          <DialogTitle className="flex items-center gap-2 text-xl">
            <FileSearch className="h-6 w-6 text-blue-600" />
            分享码预览解析
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-3 max-h-[calc(90vh-100px)] overflow-y-auto scrollbar-thin scrollbar-thumb-gray-300 scrollbar-track-gray-100">
          {/* 输入区域 */}
          <div className="bg-gray-50 rounded-lg p-4">
            <div className="flex items-center gap-2 mb-3">
              <Share2 className="h-4 w-4 text-blue-600" />
              <span className="font-medium text-gray-900">分享信息输入</span>
            </div>
            
            <div className="grid grid-cols-1 md:grid-cols-2 gap-3 mb-3">
              <div className="space-y-1">
                <Label htmlFor="shareCode" className="text-sm">分享码 *</Label>
                <Input
                  id="shareCode"
                  placeholder="请输入分享码"
                  value={shareCode}
                  onChange={(e) => setShareCode(e.target.value)}
                  className="font-mono h-9"
                />
              </div>
              <div className="space-y-1">
                <Label htmlFor="accessCode" className="text-sm">访问码</Label>
                <Input
                  id="accessCode"
                  placeholder="请输入访问码（如有）"
                  value={accessCode}
                  onChange={(e) => setAccessCode(e.target.value)}
                  className="font-mono h-9"
                />
              </div>
            </div>
            
            <div className="flex gap-2">
              <Button 
                onClick={handlePreview} 
                disabled={!shareCode.trim() || isLoading}
                size="sm"
                className="flex-1"
              >
                {isLoading ? (
                  <>
                    <Loader2 className="mr-2 h-3 w-3 animate-spin" />
                    解析中...
                  </>
                ) : (
                  <>
                    <Eye className="mr-2 h-3 w-3" />
                    预览内容
                  </>
                )}
              </Button>
              
              {previewResult && (
                <Button 
                  onClick={handleAddToList} 
                  variant="outline"
                  disabled={isAdding}
                  size="sm"
                  className="flex-1"
                >
                  {isAdding ? (
                    <>
                      <Loader2 className="mr-2 h-3 w-3 animate-spin" />
                      添加中...
                    </>
                  ) : (
                    <>
                      <Plus className="mr-2 h-3 w-3" />
                      添加到列表
                    </>
                  )}
                </Button>
              )}
            </div>
          </div>

          {/* 消息提示 */}
          {(error || successMessage) && (
            <div className="space-y-2">
              {error && (
                <Alert variant="destructive" className="py-2">
                  <AlertCircle className="h-3 w-3" />
                  <AlertTitle className="text-sm">解析失败</AlertTitle>
                  <AlertDescription className="text-xs">{error}</AlertDescription>
                </Alert>
              )}
              {successMessage && (
                <Alert className="border-green-200 bg-green-50 py-2">
                  <CheckCircle className="h-3 w-3 text-green-600" />
                  <AlertTitle className="text-green-800 text-sm">操作成功</AlertTitle>
                  <AlertDescription className="text-green-700 text-xs">{successMessage}</AlertDescription>
                </Alert>
              )}
            </div>
          )}

          {/* 预览结果 */}
          {previewResult && (
            <>
              {/* 统计信息 */}
              <div className="grid grid-cols-2 md:grid-cols-4 gap-2">
                <div className="bg-blue-50 rounded p-2 text-center">
                  <File className="h-4 w-4 mx-auto mb-1 text-blue-600" />
                  <div className="text-lg font-bold text-blue-700">{previewResult.statistics?.totalFiles || 0}</div>
                  <div className="text-xs text-blue-600">文件</div>
                </div>
                <div className="bg-green-50 rounded p-2 text-center">
                  <HardDrive className="h-4 w-4 mx-auto mb-1 text-green-600" />
                  <div className="text-lg font-bold text-green-700">{formatBytes(previewResult.statistics?.totalSize || 0)}</div>
                  <div className="text-xs text-green-600">大小</div>
                </div>
                <div className="bg-purple-50 rounded p-2 text-center">
                  <User className="h-4 w-4 mx-auto mb-1 text-purple-600" />
                  <div className="text-sm font-bold text-purple-700 truncate">{previewResult.shareInfo.creator?.nickName || '未知'}</div>
                  <div className="text-xs text-purple-600">创建者</div>
                </div>
                <div className="bg-orange-50 rounded p-2 text-center">
                  <FolderOpen className="h-4 w-4 mx-auto mb-1 text-orange-600" />
                  <div className="text-lg font-bold text-orange-700">{previewResult.statistics?.totalFolders || 0}</div>
                  <div className="text-xs text-orange-600">文件夹</div>
                </div>
              </div>
              
              {/* 分享详情 */}
              <div className="bg-gray-50 rounded-lg p-3">
                <div className="flex items-center gap-2 mb-2">
                  <Share2 className="h-4 w-4 text-gray-600" />
                  <span className="font-medium text-gray-900">分享详情</span>
                </div>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-2 text-sm">
                  <div className="flex items-center gap-2">
                    <Badge variant="outline" className="text-blue-600 border-blue-200 text-xs px-2 py-0.5">
                      标题
                    </Badge>
                    <span className="font-medium text-gray-900 truncate">
                      {previewResult.shareInfo.shareName || '未知'}
                    </span>
                  </div>
                  <div className="flex items-center gap-2">
                    <Badge variant="outline" className="text-green-600 border-green-200 text-xs px-2 py-0.5">
                      分享码
                    </Badge>
                    <span className="font-mono text-xs text-gray-900">
                      {previewResult.shareInfo.shareCode}
                    </span>
                  </div>
                  <div className="flex items-center gap-2">
                    <Badge variant="outline" className="text-purple-600 border-purple-200 text-xs px-2 py-0.5">
                      ID
                    </Badge>
                    <span className="font-mono text-xs text-gray-900">
                      {previewResult.shareInfo.shareId}
                    </span>
                  </div>
                  <div className="flex items-center gap-2">
                    <Badge variant="outline" className="text-orange-600 border-orange-200 text-xs px-2 py-0.5">
                      深度
                    </Badge>
                    <span className="text-xs text-gray-900">
                      {previewResult.statistics?.maxDepthReached || 0} 层
                    </span>
                  </div>
                </div>
                
                {/* 文件类型统计 */}
                {previewResult.statistics?.fileTypes && Object.keys(previewResult.statistics.fileTypes).length > 0 && (
                  <div className="mt-2">
                    <div className="flex items-center gap-2 mb-1">
                      <Badge variant="outline" className="text-indigo-600 border-indigo-200 text-xs px-2 py-0.5">
                        文件类型
                      </Badge>
                    </div>
                    <div className="flex flex-wrap gap-1">
                      {Object.entries(previewResult.statistics.fileTypes).map(([type, count]) => (
                        <Badge key={type} variant="secondary" className="text-xs px-1.5 py-0.5">
                          {type.toUpperCase()}: {count}
                        </Badge>
                      ))}
                    </div>
                  </div>
                )}
              </div>
              
              {/* 文件结构 */}
              <div className="bg-gray-50 rounded-lg">
                <div className="flex items-center justify-between p-3 border-b border-gray-200">
                  <div className="flex items-center gap-2">
                    <FolderOpen className="h-4 w-4 text-gray-600" />
                    <span className="font-medium text-gray-900">文件结构</span>
                  </div>
                  <Badge variant="outline" className="text-xs">
                    共 {(previewResult.statistics?.totalFiles || 0) + (previewResult.statistics?.totalFolders || 0)} 项
                  </Badge>
                </div>
                <div className="h-80 overflow-y-auto scrollbar-thin scrollbar-thumb-gray-300 scrollbar-track-gray-100">
                  <ExpandableFileTree nodes={previewResult.fileInfo || []} />
                </div>
              </div>
            </>
          )}
        </div>
      </DialogContent>
    </Dialog>
  );
}

export default ShareCodePreviewDialog;